<template>
    <div v-if="loading" style="position: fixed;top: 0;left: 0;width: 100%;height: 100%;z-index: 99;display: flex;justify-content: center;align-items: center;background-color: rgba(0,0,0,0.7);">
        <van-loading />
    </div>
    <div class="main">
        <div class="main-continue">
            <van-radio-group v-model="form.floor" direction="horizontal">
                <van-radio name="2">2楼</van-radio>
                <van-radio name="3">3楼</van-radio>
                <van-radio name="4">4楼</van-radio>
            </van-radio-group>
        </div>
        <div class="main-continue">
            <van-radio-group v-model="form.isMaterial" direction="horizontal">
                <van-radio name="M">原料</van-radio>
                <van-radio name="PT">盘头</van-radio>
            </van-radio-group>
        </div>
        <div class="main-continue" style="padding-left: 0;">
            <van-field v-model="getDispatchValue" is-link readonly label="仓库区域" placeholder="请选择仓库区域"
                @click="showPicker = true" />
            <van-popup v-model:show="showPicker" round position="bottom">
                <van-picker :columns="warehouseArea" @cancel="showPicker = false" @confirm="onConfirm" />
            </van-popup>
        </div>
        <div class="main-continue" style="padding-left: 0;">
            <div style="display: flex;align-items: center;flex-direction: row-reverse;gap: 10px;">
                <div style="display: flex;align-items: center;" v-for="value in TypeList">
                    <div class="child" :style="'background:' + value.color"></div>
                    <div style="padding-left: 3px;">{{ value.label }}</div>
                </div>
            </div>
            <div style="padding: 10px;text-align: right;">
                库位按钮长按触可查看详情
            </div>
            
        </div>
    </div>
     <van-checkbox-group v-model="form.comeLocationList" class="w-100 ma-0 custom-checkbox" style="padding: 20px;padding-bottom: 100px;"
                    direction="horizontal" @change="onComeChange">

                    <div v-for="(item, index) in comeLocation" :key="index">
                        <div style="display: flex;justify-content: left;flex-wrap: wrap;">
                          <div v-for="value in item.locationRets">
                            <van-checkbox  
                            
                            @touchstart="startLongPress(valuse)"
                            @touchend="cancelLongPress"
                            @touchcancel="cancelLongPress"
                            
                            v-for="valuse in value.locationRets" :name="valuse.locationCode"
                              :disabled="valuse.state == 10 || !isSpecify">
                              {{ valuse.locationName.split('_')[1] }}
                              <template #icon="props">
                                <div class="pos-rel">
                                  <div class="checkbox-svg keep-px"
                                    :style="'background:' + handleWarehouseColor(props.checked, valuse.state, valuse.state !== '10' || !isSpecify)">
                                    <van-icon v-show="!!props.checked" name="success" size="10" />
                                  </div>
                                </div>
                              </template>
                            </van-checkbox>
                          </div>
                        </div>

                        <!--                        :disabled="item.state !== '20'" -->

                      </div>


                  </van-checkbox-group>
    <van-button @click="getWmsLocationListRelaseS" v-if="isSpecify" style="position: fixed;width: 100%;bottom: 0;" type="primary">修改空闲状态</van-button>
    <van-button @click="gotoBack" v-else style="position: fixed;width: 100%;bottom: 0;" type="primary">关闭</van-button>
</template>
<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router';
import { getWmsHouseMap, getWmsLocationList, getWmsLocationListRelase } from '../../api/pda';
import { getInfo } from '../../api/login';
import useStore from '@/store/index';
const { usePDAStore } = useStore();
const router = useRouter();
const timer = ref(null);
const isLongPress = ref(false);
const isSpecify = ref(false);
const form = ref({
    floor: '2',
    isMaterial: 'M',
    locationCode: '',
    comeLocationList:[]
})
const warehouseArea = ref([])
const comeLocation = ref([])
const floorList = ref({
    '1': [[{ label: 'A1', id: '1', value: 'A1', type: '' }, { label: 'A2', id: '2', value: 'A2' }, { label: 'A3', id: '3', value: 'A3' }]
        , [{ label: 'B1', id: '4', value: 'B1' }, { label: 'B2', id: '6', value: 'B2' }, { label: 'B3', id: '7', value: 'B3' }]
        , [{ label: 'C1', id: '8', value: 'C1' }, { label: 'C2', id: '9', value: 'C2' }, { label: 'C3', id: '10', value: 'C3' }]],
    '2': [[]],
    '3': [[]],
})
const showPicker = ref(false);
const TypeList = ref([{
    label: '占用',
    value: '1',
    color: 'green'
}, {
    label: '锁定',
    value: '2',
    color: 'yellow'
}, {
    label: '空闲',
    value: '3',
    color: 'darkgray'
}, {
    label: '异常',
    value: '4',
    color: 'orange'
}, {
    label: '禁用',
    value: '5',
    color: 'red'
}
])
const loading = ref(false);
const onComeChange = () => {

}
const gotoBack = () => {
     router.push(router.options.history.state.back)
}
function handleWarehouseColor(checked, state, dis) {
  if (checked) {
    return 'rgb(25, 137, 250)'
  }

  const config = {
    '20': 'green',
    '50': 'yellow',
    '10': 'darkgray',
    '30': 'orange',
    '40': 'red',
  }
  return config[state]
}
const getDispatchValue = computed(() => {
    return warehouseArea.value.find(item => item.value === form.value.locationCode)?.text || '';
});
const onConfirm = ({ selectedValues }) => {
    form.value.locationCode = selectedValues[0];
    showPicker.value = false;
};
// 开始计时（判断长按）
const startLongPress = (e) => {
    isLongPress.value = false;
    timer.value = setTimeout(() => {
        isLongPress.value = true;
        handleLongPress(e);
    }, 500); // 500ms 视为长按
};

// 取消计时（如果是点击）
const cancelLongPress = () => {
    if (timer.value) {
        clearTimeout(timer.value);
        timer.value = null;
    }
};
const getWmsLocationListRelaseS = async () => {
      function customSort(a, b) {
    // 使用正则表达式提取两个数字部分
    const regex = /-(\d+)-(\d+)$/;
    const [, numA1, numA2] = a.match(regex).map(Number);
    const [, numB1, numB2] = b.match(regex).map(Number);

    // 先比较第一个数字（组排序）
    if (numA1 !== numB1) {
      return numA1 - numB1;
    }
    // 如果第一个数字相同，比较第二个数字（组内排序）
    return numA2 - numB2;
  }
    console.log(form.value.comeLocationList)
    if(form.value.comeLocationList && form.value.comeLocationList.length > 0) {
          const result = await getWmsLocationListRelase({
        locationCodes: form.value.comeLocationList.sort(customSort)
    })
    init();
    }
  
}
// 点击事件
const handleClick = (e) => {
    if (isLongPress.value) {
        console.log("这是长按，不触发点击");
        return;
    }
    console.log("点击事件", e);
};

// 长按事件
const handleLongPress = (e) => {
    console.log("长按事件", e);
    
   usePDAStore.setShowForm({...e,isMaterial:form.value.isMaterial})
   router.push('/inventoryDetail')
};

const init = async () => {
    loading.value = true;
    const result = await getWmsHouseMap({
        floor: form.value.floor,
        isMaterial: form.value.isMaterial
    });
    if (result.code == '00000') {
        warehouseArea.value = Object.entries(result.data).map(([key, value]) => ({ text: value, value: key }));
    } else {
        warehouseArea.value = []
    }
    form.value.locationCode = ''
     comeLocation.value = []
     form.value.comeLocationList = []
     loading.value = false;
}

watch([() => form.value.locationCode], () => {
  initPower();
});
 
watch([() => form.value.isMaterial, () => form.value.floor], () => {
  init();
});

const initPower = async () => {
    if (!form.value.locationCode) return;
    loading.value = true;

    comeLocation.value = []
    form.value.comeLocationList = []
    const result = await getWmsLocationList({
        floor: form.value.floor,
        isMaterial: form.value.isMaterial,
        locationCode: form.value.locationCode
    })
    if (result.code == '00000') {
        comeLocation.value = result.data;
    }else{
        comeLocation.value = []
    }
    loading.value = false;
}

const getInfoS = async () => {
  const result = await getInfo()
  if (result.code == '00000') {
    if(result.data.permissions = '*:*:*'){
        isSpecify.value = true;
    }else if(result.data.permissions.includes('wms:warehouse:update')){
        isSpecify.value = true;
    }
  }
}
onMounted(() => {
    init();
    getInfoS();
})

</script>
<style scoped lang="scss">
.main {
    .main-continue {
        padding: 15px;
        font-size: 13px;

        .child {
            width: 14px;
            height: 14px;
            background: #f2f3f5;
            border-radius: 4px;
        }

        .childPower {
            width: 40px;
            height: 40px;
            background: #f2f3f5;
            border-radius: 4px;
        }

        .childText {
            text-align: center;
            font-size: 12px;
        }
    }

   

}
 .custom-checkbox {
  .van-grid-item__content {
    padding: 0
  }

  .van-checkbox__icon--checked .van-icon {
    border-color: transparent;
    background-color: transparent;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  :deep(.van-grid-item__content) {
    padding: 0 !important;
  }

  .checkbox-svg {
    width: 22px;
    height: 22px;

    svg {
      background-color: #13b058;
    }
  }

  .van-checkbox {
    //display: block;
    margin-right: 0;
    margin-bottom: 10px;
    flex-direction: column;
    align-items: center;

    :deep(.van-checkbox__label) {
      margin-left: 0 !important;
    }
  }
}
</style>